﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import '../../../gen/assets.gen.dart';
import '../../../common/res/gaps.dart';

/// 整年日历页面
class YearCalendarView extends StatefulWidget {
  const YearCalendarView({super.key});

  @override
  State<YearCalendarView> createState() => _YearCalendarViewState();
}

class _YearCalendarViewState extends State<YearCalendarView> {
  DateTime _currentDate = DateTime.now();
  int _selectedYear = DateTime.now().year;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
            size: 20,
          ),
          onPressed: () => Get.back(),
        ),
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 左侧年份导航按钮
            IconButton(
              onPressed: _previousYear,
              icon: Assets.status.preMonth.image(
                width: 24,
                height: 24,
              ),
            ),
            Gaps.hGap16,
            // 中间年份显示
            Text(
              '${_selectedYear}年',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
            Gaps.hGap16,
            // 右侧年份导航按钮
            IconButton(
              onPressed: _nextYear,
              icon: Assets.status.nextMonth.image(
                width: 24,
                height: 24,
              ),
            ),
            
            SizedBox(width: 16.w),
          ],
        ),
        centerTitle: true,
      ),
      body: Container(
        margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
        child: _buildYearCalendar(),
      ),
    );
  }

  Widget _buildYearCalendar() {
    return GridView.builder(
      padding: EdgeInsets.zero,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: 0.65, // 调整宽高比，让卡片更高
        crossAxisSpacing: 8.w,
        mainAxisSpacing: 8.h,
      ),
      itemCount: 12,
      itemBuilder: (context, index) {
        final month = index + 1;
        final isCurrentMonth = _isCurrentMonth(month);
        final hasData = _hasMonthData(month);

        return GestureDetector(
          onTap: () => _onMonthTap(month),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.transparent,
              borderRadius: BorderRadius.circular(8.r),
              border: isCurrentMonth
                  ? Border.all(color: const Color(0xffF46425), width: 1)
                  : Border.all(color: const Color(0xff212121), width: 1),
            ),
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 6.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    _getMonthName(month),
                    style: TextStyle(
                      color:
                          isCurrentMonth ? const Color(0xffF46425) : Colors.white,
                      fontSize: 15.sp,
                      fontWeight:
                          isCurrentMonth ? FontWeight.bold : FontWeight.normal,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Expanded(
                    child: _buildMonthDays(month, isCurrentMonth),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildMonthDays(int month, bool isCurrentMonth) {
    final firstDay = DateTime(_selectedYear, month, 1);
    final lastDay = DateTime(_selectedYear, month + 1, 0);
    final daysInMonth = lastDay.day;
    final firstWeekday = firstDay.weekday; // 1=周一, 7=周日

    // 创建日期网格
    List<Widget> dayWidgets = [];

    // 添加空白占位符（当月第一天之前的空位）
    for (int i = 1; i < firstWeekday; i++) {
      dayWidgets.add(SizedBox(width: 14.w, height: 14.h));
    }

    // 添加当月的日期
    for (int day = 1; day <= daysInMonth; day++) {
      final hasData = _hasDayData(_selectedYear, month, day);
      dayWidgets.add(
        Container(
          width: 14.w,
          height: 14.h,
          alignment: Alignment.center,
          child: Text(
            day.toString(),
            style: TextStyle(
              color: hasData
                  ? const Color(0xffF46425)
                  : Colors.white.withOpacity(0.6),
              fontSize: 9.sp,
              fontWeight: hasData ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 4.w),
      child: Wrap(
        spacing: 1.w,
        runSpacing: 1.h,
        alignment: WrapAlignment.center,
        children: dayWidgets,
      ),
    );
  }

  String _getMonthName(int month) {
    const monthNames = [
      '一月', '二月', '三月', '四月', '五月', '六月',
      '七月', '八月', '九月', '十月', '十一月', '十二月'
    ];
    return monthNames[month - 1];
  }

  bool _isCurrentMonth(int month) {
    return _selectedYear == _currentDate.year && month == _currentDate.month;
  }

  bool _hasMonthData(int month) {
    // 模拟数据：某些月份有数据
    final monthsWithData = [1, 2, 3, 8, 9, 10, 11, 12];
    return monthsWithData.contains(month);
  }

  bool _hasDayData(int year, int month, int day) {
    // 模拟数据：某些日期有数据
    final datesWithData = [
      DateTime(2024, 1, 10), DateTime(2024, 1, 11), DateTime(2024, 1, 12),
      DateTime(2024, 1, 27), DateTime(2024, 1, 28), DateTime(2024, 1, 29),
      DateTime(2024, 2, 3), DateTime(2024, 2, 4), DateTime(2024, 2, 5),
      DateTime(2024, 3, 1), DateTime(2024, 3, 2), DateTime(2024, 3, 3),
      DateTime(2024, 8, 1), DateTime(2024, 8, 2), DateTime(2024, 8, 3),
    ];
    
    return datesWithData.any((date) => 
        date.year == year && date.month == month && date.day == day);
  }

  void _previousYear() {
    setState(() {
      _selectedYear--;
    });
  }

  void _nextYear() {
    setState(() {
      _selectedYear++;
    });
  }

  void _onMonthTap(int month) {
    // 返回选中的月份到上一个页面
    Get.back(result: DateTime(_selectedYear, month));
  }
}
